<template>
  <div class="course-list">
    <el-card class="course-card">
      <template #header>
        <div class="card-header">
          <span>课程列表</span>
          <div class="header-actions">
            <el-select
              v-model="searchForm.categoryId"
              placeholder="请选择分类"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入课程名称"
              style="width: 200px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">添加课程</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="courseList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="课程名称" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="duration" label="时长(分钟)" width="120" />
        <el-table-column prop="capacity" label="容量" width="80" />
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="scope">
            <el-tag :type="getDifficultyTagType(scope.row.difficulty)">
              {{ formatDifficulty(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseRules"
        label-width="100px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name" :maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="课程分类" prop="categoryId">
          <el-select v-model="courseForm.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程时长" prop="duration">
          <el-input-number
            v-model="courseForm.duration"
            :min="1"
            :max="300"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最大容量" prop="capacity">
          <el-input-number
            v-model="courseForm.capacity"
            :min="1"
            :max="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="课程难度" prop="difficulty">
          <el-rate
            v-model="courseForm.difficulty"
            :max="3"
            :texts="['初级', '中级', '高级']"
            show-text
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-input v-model="courseForm.coverImage" placeholder="请输入图片URL" :maxlength="200" />
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input v-model="courseForm.description" type="textarea" :maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-switch
            v-model="courseForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  Course,
  CourseCategory,
  CreateCourseRequest,
  UpdateCourseRequest
} from '@/types/api/course'
import { courseApi } from '@/api/modules/course'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const courseList = ref<Course[]>([])
const categories = ref<CourseCategory[]>([])

const searchForm = reactive({
  keyword: '',
  categoryId: undefined as number | undefined
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const courseFormRef = ref()
const currentCourseId = ref(0)

// 表单数据
const courseForm = reactive({
  name: '',
  categoryId: undefined as number | undefined,
  duration: 60,
  capacity: 20,
  difficulty: 1,
  coverImage: '',
  description: '',
  status: 1
})

// 表单验证规则
const courseRules = {
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入课程时长', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入最大容量', trigger: 'blur' }
  ]
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty: number) => {
  switch (difficulty) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'danger'
    default: return 'info'
  }
}

// 格式化难度显示
const formatDifficulty = (difficulty: number) => {
  switch (difficulty) {
    case 1: return '初级'
    case 2: return '中级'
    case 3: return '高级'
    default: return '未知'
  }
}

// 获取课程列表
const getCourseList = async () => {
  loading.value = true
  try {
    const response = await courseApi.getCourseList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      categoryId: searchForm.categoryId
    })
    courseList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 获取课程分类
const getCourseCategories = async () => {
  try {
    const response = await courseApi.getCourseCategories()
    categories.value = response.data.data
  } catch (error) {
    ElMessage.error('获取课程分类失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getCourseList()
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.keyword = ''
  searchForm.categoryId = undefined
  pagination.page = 1
  getCourseList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getCourseList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getCourseList()
}

// 添加课程
const handleAdd = () => {
  dialogTitle.value = '添加课程'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(courseForm, {
    name: '',
    categoryId: undefined,
    duration: 60,
    capacity: 20,
    difficulty: 1,
    coverImage: '',
    description: '',
    status: 1
  })
}

// 编辑课程
const handleEdit = (row: Course) => {
  dialogTitle.value = '编辑课程'
  isEdit.value = true
  dialogVisible.value = true
  currentCourseId.value = row.id
  // 填充表单数据
  Object.assign(courseForm, {
    name: row.name,
    categoryId: row.categoryId,
    duration: row.duration,
    capacity: row.capacity,
    difficulty: row.difficulty,
    coverImage: row.coverImage,
    description: row.description,
    status: row.status
  })
}

// 查看课程详情
const handleView = (row: Course) => {
  dialogTitle.value = '课程详情'
  isEdit.value = false
  dialogVisible.value = true
  currentCourseId.value = row.id
  // 填充表单数据
  Object.assign(courseForm, {
    name: row.name,
    categoryId: row.categoryId,
    duration: row.duration,
    capacity: row.capacity,
    difficulty: row.difficulty,
    coverImage: row.coverImage,
    description: row.description,
    status: row.status
  })
}

// 删除课程
const handleDelete = (row: Course) => {
  formUtils.handleDeleteConfirm(`课程 "${row.name}"`, async () => {
    await courseApi.deleteCourse(row.id)
    getCourseList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存课程信息
const handleSave = async () => {
  if (!courseFormRef.value) return

  await courseFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      const submitKey = isEdit.value ? `update_course_${currentCourseId.value}` : 'create_course'

      try {
        await preventDuplicateSubmit(submitKey, async () => {
          saveLoading.value = true
          try {
            await formUtils.handleCreateUpdate(
              isEdit.value,
              () => {
                // 添加课程
                const createData: CreateCourseRequest = {
                  categoryId: courseForm.categoryId!,
                  name: courseForm.name,
                  description: courseForm.description,
                  coverImage: courseForm.coverImage,
                  duration: courseForm.duration,
                  capacity: courseForm.capacity,
                  difficulty: courseForm.difficulty
                }
                return courseApi.createCourse(createData)
              },
              () => {
                // 编辑课程
                const updateData: UpdateCourseRequest = {
                  categoryId: courseForm.categoryId,
                  name: courseForm.name,
                  description: courseForm.description,
                  coverImage: courseForm.coverImage,
                  duration: courseForm.duration,
                  capacity: courseForm.capacity,
                  difficulty: courseForm.difficulty,
                  status: courseForm.status
                }
                return courseApi.updateCourse(currentCourseId.value, updateData)
              },
              {
                successCallback: () => {
                  dialogVisible.value = false
                  getCourseList()
                }
              }
            )
          } catch (error: any) {
            throw error // 重新抛出错误以确保防重复提交正确处理
          } finally {
            saveLoading.value = false
          }
        })
      } catch (error: any) {
        // 防重复提交保护捕获的错误
        if (error.message === '请勿重复提交') {
          ElMessage.warning('请勿重复提交')
        }
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(courseFormRef.value, courseForm, {
    name: '',
    categoryId: undefined,
    duration: 60,
    capacity: 10,
    difficulty: 'BEGINNER',
    coverImage: '',
    description: '',
    status: 1
  })
}

// 初始化
onMounted(() => {
  getCourseList()
  getCourseCategories()
})
</script>

<style scoped lang="scss">
.course-list {
  .course-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
